<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    var list = [
      {id: '1', pid: '', name: '总裁办'},
      {id: '2', pid: '', name: '行政部'},
      {id: '3', pid: '', name: '人事部'},
      {id: '4', pid: '', name: '财务部'},
      {id: '5', pid: '4', name: '出纳'},
      {id: '6', pid: '4', name: '审计'},
      {id: '7', pid: '2', name: '学工'},
      {id: '8', pid: '1', name: '教研部'},
      {id: '9', pid: '8', name: 'java'},
      {id: '10', pid: '8', name: '前端'},
      {id: '11', pid: '8', name: 'python'}
    ]
    // list转换成tree
    function ListToTree(list, pid = '') {
      const newList = []
      list.forEach(item => {
        if (item.pid === pid) {
          let result = ListToTree(list, item.id)
          if (result.length > 0) {
            item.children = result
          }
          newList.push(item)
        }
      })
      return newList
    }
    console.log(ListToTree(list, ''))
// ------------------------------------------------------
    const tree = [
    {
      "id": "1",
      "pid": "",
      "name": "总裁办",
      "children": [
        {
          "id": "8",
          "pid": "1",
          "name": "教研部",
          "children": [
            {
              "id": "9",
              "pid": "8",
              "name": "java"
            },
            {
              "id": "10",
              "pid": "8",
              "name": "前端"
            },
            {
              "id": "11",
              "pid": "8",
              "name": "python"
            }
          ]
        }
      ]
    },
    {
      "id": "2",
      "pid": "",
      "name": "行政部",
      "children": [
        {
          "id": "7",
          "pid": "2",
          "name": "学工"
        }
      ]
    },
    {
      "id": "3",
      "pid": "",
      "name": "人事部"
    },
    {
      "id": "4",
      "pid": "",
      "name": "财务部",
      "children": [
        {
          "id": "5",
          "pid": "4",
          "name": "出纳"
        },
        {
          "id": "6",
          "pid": "4",
          "name": "审计"
        }
      ]
    }
  ]
    // tree转list
    function TreeToList(tree) {
      let newList = []
      tree.forEach(item => {
        newList.push(item)
        if (item.children) {
          let result = TreeToList(item.children)
          newList = [...newList, ...result]
          delete item.children
        }
      })
      return newList
    }
    console.log(TreeToList(tree))
  </script>
</body>
</html>